package communication

import (
	"fmt"
	"log"
	"net"
	"strconv"
	"time"
)

const Host = "192.168.1.103"
const Port = 9999
const AsyncPort = 9998
const ReconnectTime = 3 * time.Second

type ClientComm struct {
	conn net.Conn
}

func (client *ClientComm) init(host string, port int) {
	for {
		conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port))
		if err != nil {
			continue
		}
		client.conn = conn
		break
	}
}

func (client *ClientComm) Close() {
	if client.conn != nil {
		err := client.conn.Close()
		if err != nil {
			log.Printf("关闭连接失败，原因：%s", err)
		}
		client.conn = nil
	}
}

func (client *ClientComm) write(b []byte) {
	_, err := client.conn.Write(b)
	if err != nil {
		panic(err)
	}
}

func (client *ClientComm) sendBytes(message []byte) {
	length := fmt.Sprintf("%d", len(message))
	n := fmt.Sprintf("%05d", len(length))
	client.write([]byte(n))
	client.write([]byte(length))
	client.write(message)
}

func (client *ClientComm) read(n int) []byte {
	buffer := make([]byte, n)
	_, err := client.conn.Read(buffer)
	if err != nil {
		panic(err)
	}
	return buffer
}

func (client *ClientComm) recvBytes() []byte {
	n, err := strconv.Atoi(string(client.read(5)))
	if err != nil {
		panic(err)
	}
	length, err := strconv.Atoi(string(client.read(n)))
	if err != nil {
		panic(err)
	}
	return client.read(length)
}
